﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using ToolBoxPro;
using System.Net.Mail;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using LinqObj;
/// <summary>
/// Summary description for Notifications
/// </summary>
public class Notifications
{
    public bool mailSent = false;

    private string _mailTo;
    private string _mailSubject;
    private string _message;
    private MailPriority _priority;
    private static string templateFolder = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/");
    private static string EmailEncoding = System.Configuration.ConfigurationManager.AppSettings["Email.Encoding"];

    public Notifications(Order order)
    {
        Supplier _supplier = order.Service.Supplier;
        this._mailTo = _supplier.supplier_email;
        this._mailSubject = _supplier.supplier_name + " " + order.Service.service_description + " from " + order.Agent.agent_name + " in " + order.Agent.Agent_Group;
        this._priority = MailPriority.High;
        this._message = readFile(Path.Combine(templateFolder, "noitification_supplier.htm"));
        this._message = orderMailHelper(this._message, order, order.Agent, order.Service);
    }

    public Notifications(string mailTo, string mailSubject, string message)
    {
        this._mailTo = mailTo;
        this._mailSubject = mailSubject;
        this._priority = MailPriority.High;
        this._message = message;
    }


    public Notifications() { }

    private string orderMailHelper(string _html, Order order, Agent agent, Service service)
    {
        /*
         * $agentName
         * $otherAgents
         * $agentNumber
         * $agentEmail
         * $orderID
         * $orderItem
         * $orderRequestedDate
         */

        Property property = Property.GetPropertyByOrderID(order.order_id);

        _html = _html.Replace("$agentName", agent.agent_name);
        string otherAgents = String.Format("Listing Agent: {0}\nAdvertising Agent: {1}\n Managing Agent:{2}", 
                                                property.Agent2, property.Agent, property.Agent3);
        _html = _html.Replace("$otherAgents", otherAgents);
        _html = _html.Replace("$agentNumber", agent.agent_name);
        _html = _html.Replace("$agentEmail", agent.email_address);
        _html = _html.Replace("$orderID", order.order_id.ToString());
        _html = _html.Replace("$orderRequestedDate", order.order_date.ToString("d", CultureInfo.CurrentCulture));
        _html = _html.Replace("$orderItem", service.service_description);
        return _html;
    }

    private string readFile(string filePath)
    {
        String content = "";
        string[] lines = System.IO.File.ReadAllLines(filePath);
        foreach (string line in lines)
        {
            content += line + "\n";
        }
        return content;

    }

    public bool BeforeSend() { return true; }

    public void SendEmail()
    {
        //if (!BeforeSend())
        MailMessage _mail = new MailMessage();
        _mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        _mail.To.Add(new MailAddress(_mailTo));
        _mail.IsBodyHtml = true;
        _mail.Subject = _mailSubject;
        _mail.Body = _message;
        _mail.BodyEncoding = System.Text.Encoding.UTF8;
        _mail.Priority = MailPriority.High;
        _mail.BodyEncoding = System.Text.Encoding.GetEncoding(EmailEncoding);
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
        smtpClient.Send(_mail);
    }

    protected void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
    {
        // Get the unique identifier for this asynchronous operation.
        String token = (string)e.UserState;

        if (e.Cancelled)
        {
            Console.WriteLine("[{0}] Send canceled.", token);
        }
        if (e.Error != null)
        {
            Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
        }
        else
        {
            Console.WriteLine("Message sent.");
        }
        mailSent = true;
        Console.WriteLine("amilSent={0}", mailSent);
    }

}
